<template>
  <div style="width: 100%;height: 100%;display:flex;flex-direction: column;justify-content: space-between">
    <div style="display: flex">
      <input id="fileInput" type="file" name="file" :disabled="uploading" @change="fileChange"/>
      <div class="dragDropArea" v-on:drop="onDrop" v-on:dragover="onDragover">拖拽上传区域</div>
    </div>
    <div>
      <el-button size="small" type="primary" @click="upload" :disabled="uploading">分片上传</el-button>
      <el-button size="small" type="danger" @click="stop">暂停上传</el-button>
      <el-button size="small" type="primary" @click="continueUpload">继续上传</el-button>
      <el-button size="small" type="primary" @click="clearFiles">清除已选择文件</el-button>
    </div>
    <div>
      <p>上传进度</p>
      <el-progress :percentage="currentPercentage"/>
    </div>
    <div>
      <p>文件位置:</p>
      <a :href="uploading ? '' : uploadUrl" target="_blank">{{ uploading ? '' : uploadUrl }}</a>
      <br>
    </div>
  </div>
</template>

<script setup>
import {computed, ref} from 'vue';
import {uploadFile, stopUploadFile, continueUploadFile} from "@/untils/uploadFile";
import store from '@/store/index'

let uploadFileName = ref('')
let uploading = ref(false)
let uploadUrl = ref('')

// 文件变更
const fileChange = (e) => {
  const file = document.getElementById('fileInput').files[0];
  uploadFileName.value = file?.name?.split('.')[0]
  store.commit('SET_PROCESS', {name: uploadFileName.value, progress: 0})
  store.commit('SET_UPLOAD_URL', {name: uploadFileName.value, url: ''})
}
// 上传
const upload = async () => {
  const file = document.getElementById('fileInput').files[0];
  uploading.value = true
  await uploadFile(file).then(res => {
    //上传成功后的操作
    uploading.value = false
    uploadUrl.value = res?.data?.url
  })
}
// 暂停上传
const stop = async () => {
  const file = document.getElementById('fileInput').files[0];
  stopUploadFile(file)
}
// 继续上传
const continueUpload = async () => {
  const file = document.getElementById('fileInput').files[0];
  uploadFileName.value = file?.name?.split('.')[0]
  continueUploadFile(file)
}
// 清除已选择文件
const clearFiles = () => {
  const file = document.getElementById('fileInput');
  file.value = ''
}

const progressCfg = computed(() => store.state.progressCfg)
const currentPercentage = computed(() => Number(store.state.progressCfg[uploadFileName.value] || 0))

const onDragover = (e) => {
  e.preventDefault()
}
const onDrop = (e) => {
  e.preventDefault();
  const files = e.dataTransfer.files;
  const file = document.getElementById('fileInput');
  file.files = files
}
</script>

<style scoped>
.dragDropArea {
  width: 250px;
  height: 40px;
  background-color: #e9f8ff;
}
</style>